import {
  createRouter,
  createWebHashHistory
} from 'vue-router';
import Upload from '@/views/Upload.vue';
import Msite from '@/views/Msite.vue';
import Cookies from 'js-cookie';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import Order from '../views/Order.vue';
import Search from '../views/Search.vue';
import component from 'element-plus/es/components/tree-select/src/tree-select-option.mjs';
import Profile from '../views/profile.vue';
import ShopDetail from '../views/ShopDetail.vue';


// import component from 'element-plus/es/components/tree-select/src/tree-select-option.mjs';
// 定义路由
const routes = [
  {
    path: '/',
    name: 'Login',
    component: Upload,
    meta: { requiresAuth: false } // 登录页面不需要认证
  },
  {
    path: '/Msite',
    name: 'Msite',
    component: Msite,
    meta: { requiresAuth: true }
  },
  {
    path: '/Order',
    name: 'Order',
    component: Order,
    meta: { requiresAuth: true }
  },
  {
    path: '/Profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true }
  },
  {
    path: '/Search',
    name: 'Search',
    component: Search,
    meta: { requiresAuth: true }
  },
  {
    path: '/ShopDetail/:merchantId',
    name: 'ShopDetail',
    component: ShopDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/order/confirm/:merchantId',
    name: 'OrderConfirm',
    component: () => import('@/views/OrderConfirm.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/payment-return',
    name: 'PaymentReturn',
    component: () => import('@/views/PaymentReturn.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/order/detail/:orderId',
    name: 'OrderDetail',
    component: () => import('@/views/OrderDetail.vue'),
    meta: { requiresAuth: true },
    props: true
  }

];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const token = Cookies.get('usertoken');

  if (requiresAuth && !token) {

    // 如果目标路由需要认证且用户未登录，则重定向到登录页
    next({ name: 'Login' });
  } else if (requiresAuth && token) {

    try {
      // 验证令牌的有效性，这里假设有一个API可以用来检查令牌
      const response = await axios.post(
        `${API_BASE_URL}/checktoken`, // 提供完整的API端点URL
        null, // 如果API不需要请求体，可以传入一个空对象
        {
          headers: {
            Authorization: `Bearer ${token}` // 在请求头中添加令牌
          }
        }
      );


      if (response.status === 200) {
        // 令牌有效，允许访问
        next();
      } else {
        // 令牌无效，清除令牌并重定向到登录页
        Cookies.remove('token');
        next({ name: 'Login' });
      }
    } catch (error) {

      // 如果请求失败（例如网络问题），也可以选择重定向到登录页
      Cookies.remove('token');
      next({ name: 'Login' });
    }
  } else {
    // 不需要认证的路由，直接放行
    next();
  }
});



export default router;
